import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { jwtConstants } from './constants';

const AUTH_WHITELIST = ['/user/login', '/user/register'];

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}
  canActivate(context: ExecutionContext): boolean {
    const request: Request = context.switchToHttp().getRequest();
    if (AUTH_WHITELIST.includes(request.url)) {
      return true;
    }
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException('Token not found');
    }
    try {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      const result = this.jwtService.verify(token, {
        secret: jwtConstants.secret,
      });
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      request['user'] = result;
    } catch (error) {
      console.log('error ==== ', error);
      throw new UnauthorizedException('Invalid token');
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
